import * as systeProcessService from '../services/systemprocess'

export default {
  namespace: 'systemprocess',
  state: {
    list: [],
    total: null,
    page: null,
    selectList: [],
  },
  reducers: {
    save (state, { payload: { data: list, total, page } }) {
      return { ...state, list, total, page }
    },
    saveList (state, { payload: { selectList } }) {
      return { ...state, selectList }
    },
  },
  effects: {
    * fetch ({ payload: { page = 1 } }, { call, put }) {
      const { data } = yield call(systeProcessService.fetch, { page })
      yield put({
        type: 'save',
        payload: {
          data,
          total: parseInt(data.total),
          page: parseInt(page),
        },
      })
    },
    * remove ({ payload: id }, { call, put }) {
      yield call(systeProcessService.remove, id)
      yield put({ type: 'reload' })
    },
    * patch ({ payload: { id, values } }, { call, put }) {
      const { data } = yield call(systeProcessService.patch, { id, values })
      yield put({ type: 'reload' })
    },
    * create ({ payload: values }, { call, put }) {
      const result = yield call(systeProcessService.create, values)
      yield put({ type: 'add', payload: result })
    },
    * reload (action, { put, select }) {
      const page = yield select(state => state.systemprocess.page)
      yield put({ type: 'fetch', payload: { page } })
    },
    * add ({ payload: result }, { call, put }) {
      if (result.data.code === 400) {
        throw new Error(result.data.message)
      }
      yield put({ type: 'reload' })
    },
    * list ({ call, select }) {
      const { data } = yield call(systeProcessService.list)
      yield select(state => state.selectList)
      // yield put({
      //   type: 'saveList',
      //   payload: {
      //     selectList: data,
      //   },
      // })
    },
  },
  subscriptions: {
    setup ({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/systemprocess') {
          if (query === undefined) {
            query = { page: 1 }
          }
          dispatch({ type: 'fetch', payload: query })
        }
      })
    },
  },
}
